package com.sddm.printServer.service.impl;

import com.sddm.printServer.entiy.CallBack;
import com.sddm.printServer.entiy.Print;
import com.sddm.printServer.enums.CallBackEnum;
import com.sddm.printServer.service.DefaultResponseAdapter;
import com.sddm.printServer.service.InputStreamAdapter;
import com.sddm.printServer.service.PrintPdfHandler;
import com.sddm.printServer.service.PrintProcessDataAdapter;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.printing.PDFPageable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.print.PrintService;
import javax.print.attribute.HashPrintRequestAttributeSet;
import javax.websocket.Session;
import java.awt.print.PrinterJob;
import java.io.ByteArrayInputStream;
import java.util.Base64;
import java.util.List;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author wyh
 * @version 1.0
 * @date 2022/4/7 13:40
 */
@Service
public class PrintPdfHandlerImpl implements PrintPdfHandler{
    private static final Logger log = LoggerFactory.getLogger(PrintPdfHandler.class);

    @Autowired
    private PrintProcessDataAdapter printProcessDataAdapter;

    @Autowired
    private InputStreamAdapter inputStreamAdapter;

    @Autowired
    private DefaultResponseAdapter defaultResponseAdapter;

    Lock lock = new ReentrantLock();

    @Override
    public void printPdf(Print print, Session session) {
        lock.lock();
        if (print != null) {
            try {
                // 使用打印机的名称
                String printMachineName = print.getPrinter();
                String fileStream = print.getFileStream();
                // 创建打印任务
                PrinterJob job = PrinterJob.getPrinterJob();
                //获取数据流
                PDDocument document = inputStreamAdapter.getDocument(fileStream,session,print.getCustomerId());
                // 遍历所有打印机的名称
                for (PrintService ps : PrinterJob.lookupPrintServices()) {
                    String psName = ps.toString();
                    // 选用指定打印机
                    if (psName.equals(printMachineName)) {
                        job.setPrintService(ps);
                        break;
                    }
                }
                job.setPageable(new PDFPageable(document));
                HashPrintRequestAttributeSet pars = printProcessDataAdapter.printProcessData(print);
                // 开始打印
                job.print(pars);
                defaultResponseAdapter.sendMessage(new CallBack(2000, print.getCustomerId()
                        , "成功打印" + print.getCopies() + "份"), session);
                //关闭流
                document.close();

            } catch (Exception e) {
                log.error(String.valueOf(e));
                defaultResponseAdapter.sendMessage(new CallBack(CallBackEnum.PRINT_ERROR.getCode(),print.getCustomerId()
                        ,CallBackEnum.PRINT_ERROR.getMessage()),session);
            } finally {
                lock.unlock();
            }

        }
    }

    @Override
    public void MultiplePrintPdf(List<Print> print, Session session) {
        lock.lock();
        int count = 0;
        try {

            for (Print p : print) {
                if ("打印提交".equals(p.getOper())){
                    // 使用打印机的名称
                    String printMachineName = p.getPrinter();
                    String fileStream = p.getFileStream();

                    // 创建打印任务
                    PrinterJob job = PrinterJob.getPrinterJob();
                    //获取数据流
                    PDDocument document = inputStreamAdapter.getDocument(fileStream,session,print.get(0).getCustomerId());
                    // 遍历所有打印机的名称
                    for (PrintService ps : PrinterJob.lookupPrintServices()) {
                        String psName = ps.toString();
                        // 选用指定打印机
                        if (psName.equals(printMachineName)) {
                            job.setPrintService(ps);
                            break;
                        }
                    }

                    job.setPageable(new PDFPageable(document));

                    HashPrintRequestAttributeSet pars = printProcessDataAdapter.printProcessData(p);
                    // 开始打印
                    job.print(pars);
                    count+=p.getCopies();
                    //关闭流
                    document.close();
                }
            }
            defaultResponseAdapter.sendMessage(new CallBack(2000, print.get(0).getCustomerId()
                    , "成功打印" + count + "份"), session);
        } catch (Exception e) {
            log.error(String.valueOf(e));
            defaultResponseAdapter.sendMessage(new CallBack(CallBackEnum.PRINT_ERROR.getCode(),print.get(0).getCustomerId()
                    ,"成功打印" + count + "份,剩下的"+CallBackEnum.PRINT_ERROR.getMessage()),session);
        } finally {
            lock.unlock();
        }

        }


}

